﻿using AutoMapper;
using DDD.Application;
using GoodsModule.Domain.GoodsAggregate;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GoodsModule.Application.Commands
{
    public class DeductGoodsStockCommand : ICommand<Domain.GoodsAggregate.Goods>
    {
        public int OrderId { get; set; }
        public int GoodsId { get; set; }
        public int Quantity { get; set; }
    }

    public class DeductGoodsStockCommandHandler(Infrastructure.Repositories.GoodsRepository repository, IMapper mapper, ILogger<CreateGoodsCommandHandler> logger)
      : ICommandHandler<DeductGoodsStockCommand, Domain.GoodsAggregate.Goods>
    {
        public async Task<Goods> Handle(DeductGoodsStockCommand request, CancellationToken cancellationToken)
        {
            var goods = await repository.GetAsync(request.GoodsId);
            if (goods == null)
            {
                throw new Exception($"找不到id为{request.GoodsId}的商品");
            }
            //TODO: CommandHandler能不能发集成事件，还是得通过DomianEventHandler发出,
            //GoodsDeductStockFailIntegrationEvent集成事件需要OrderId 若通过DomianEvent发出 则需要附带一个无关聚合的额外OrderId
            goods.CheckAndDeductStock(request.Quantity, request.OrderId);
            return goods;
        }
    }
}
